package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class BehaviorListener {

    @Autowired
    private ApArticleService apArticleService;

    /**
     * 监听阅读数写入数据库
     * @param message
     */
    @KafkaListener(topics = ArticleConstants.READ_BEHAVIOR)
    public void onMessageRead(String message){
        Long articleId = Long.valueOf(message);
        ApArticle apArticle = apArticleService.getById(articleId);
        //获取阅读数
        Integer views = apArticle.getViews();
        apArticle.setViews(views==null?1:views+1);
        //修改阅读数量
        apArticleService.updateById(apArticle);
    }

    /**
     * 监听点赞写入数据库
     * @param message
     */
    @KafkaListener(topics = ArticleConstants.LIKES_BEHAVIOR)
    public void onMessageLikes(String message){
        LikesBehaviorDto likesBehaviorDto = JSON.parseObject(message, LikesBehaviorDto.class);

        ApArticle apArticle = apArticleService.getById(likesBehaviorDto.getArticleId());
        Integer likes = apArticle.getLikes();
        if (likesBehaviorDto.getOperation()==0){
            likes=likes==null?1:likes+1;
        }else {
            likes-=1;
        }
        apArticle.setLikes(likes);
        apArticleService.updateById(apArticle);
    }


    /**
     * 监听不喜欢 取消不喜欢
     */
    @KafkaListener(topics = ArticleConstants.COLLECTION_BEHAVIOR)
    public void onMessageUnLikes(String message){
        CollectionBehaviorDto collectionBehaviorDto = JSON.parseObject(message, CollectionBehaviorDto.class);
        ApArticle apArticle = apArticleService.getById(collectionBehaviorDto.getEntryId());
        Integer collection = apArticle.getCollection();
        if (collectionBehaviorDto.getOperation()==0){
            collection = collection==null ? 1 : collection+1;
        }else {
            collection-=1;
        }
        apArticle.setCollection(collection);
        apArticleService.updateById(apArticle);
    }


}
